/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mailclient;

import Util.EmailTools;
import dao.ThongTinTaiKhoanMailDAO;
import java.awt.Cursor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.crypto.Cipher;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.rmi.CORBA.Util;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import pojo.ThongTinTaiKhoanMail;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 *
 * @author Tuan
 */
public class SendMail extends javax.swing.JFrame {

    private Boolean isBCC = false;
    String type = "0";
    /**
     * Creates new form SendMail
     */
    public SendMail() 
    {
        initComponents();
        lblBCC.setVisible(false);
        txtBCC.setVisible(false);
        ThongTinTaiKhoanMailDAO mailInfo_DAO = new ThongTinTaiKhoanMailDAO();
        ThongTinTaiKhoanMail mailInfo = mailInfo_DAO.layThongTinTaiKhoanMail();
        if(mailInfo != null)
        {
            lblUserName.setText(mailInfo.getEmail());
        }
        
        buttonGroup4.add(rdoNotEnscryption );
        buttonGroup4.add(rdoEnscryNormal );
        buttonGroup4.add(rdoEnscryAdvanced );
        //Set Default For Enscyprt Type
        rdoNotEnscryption.setSelected(true);
        
        lblSelectKeySym.setVisible(false);
        txtSelectFilekeyForSymmetric.setVisible(false);
        btnSelectFileKeySym.setVisible(false);
        
        lblSelectKeyAsym.setVisible(false);
        txtSelectFilekey .setVisible(false);
        btnSelectFileKeyAsym.setVisible(false);
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFrame1 = new javax.swing.JFrame();
        jFrame2 = new javax.swing.JFrame();
        jFrame3 = new javax.swing.JFrame();
        jFrame4 = new javax.swing.JFrame();
        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        buttonGroup3 = new javax.swing.ButtonGroup();
        buttonGroup4 = new javax.swing.ButtonGroup();
        jInternalFrame1 = new javax.swing.JInternalFrame();
        lblUserName = new javax.swing.JLabel();
        btnLogOut = new javax.swing.JButton();
        btnSend = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtContent = new javax.swing.JTextArea();
        progressBarStatusSendEmail = new javax.swing.JProgressBar();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lblBCC = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtTo = new javax.swing.JTextField();
        txtCC = new javax.swing.JTextField();
        txtBCC = new javax.swing.JTextField();
        txtSubject = new javax.swing.JTextField();
        txtAttachFileName = new javax.swing.JTextField();
        btnFileChooser = new javax.swing.JButton();
        btnAddBCC = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        lblUserName1 = new javax.swing.JLabel();
        txtSelectFilekey = new javax.swing.JTextField();
        btnSelectFileKeyAsym = new javax.swing.JButton();
        lblSelectKeyAsym = new javax.swing.JLabel();
        txtSelectFileKeySignature = new javax.swing.JTextField();
        btnSelectFileKeySignature = new javax.swing.JButton();
        lblSelectKeySym = new javax.swing.JLabel();
        txtSelectFilekeyForSymmetric = new javax.swing.JTextField();
        btnSelectFileKeySym = new javax.swing.JButton();
        rdoEnscryNormal = new javax.swing.JRadioButton();
        rdoEnscryAdvanced = new javax.swing.JRadioButton();
        rdoNotEnscryption = new javax.swing.JRadioButton();

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jFrame2Layout = new javax.swing.GroupLayout(jFrame2.getContentPane());
        jFrame2.getContentPane().setLayout(jFrame2Layout);
        jFrame2Layout.setHorizontalGroup(
            jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame2Layout.setVerticalGroup(
            jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jFrame3Layout = new javax.swing.GroupLayout(jFrame3.getContentPane());
        jFrame3.getContentPane().setLayout(jFrame3Layout);
        jFrame3Layout.setHorizontalGroup(
            jFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame3Layout.setVerticalGroup(
            jFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jFrame4Layout = new javax.swing.GroupLayout(jFrame4.getContentPane());
        jFrame4.getContentPane().setLayout(jFrame4Layout);
        jFrame4Layout.setHorizontalGroup(
            jFrame4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame4Layout.setVerticalGroup(
            jFrame4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jInternalFrame1.setTitle("Send Email");
        jInternalFrame1.setMaximumSize(new java.awt.Dimension(1500, 2147483647));
        jInternalFrame1.setMinimumSize(new java.awt.Dimension(60, 33));
        jInternalFrame1.setPreferredSize(new java.awt.Dimension(1000, 567));
        jInternalFrame1.setVisible(true);
        jInternalFrame1.getContentPane().setLayout(null);

        lblUserName.setText("UserName");
        lblUserName.setToolTipText("");
        lblUserName.setName("lblUserName"); // NOI18N
        jInternalFrame1.getContentPane().add(lblUserName);
        lblUserName.setBounds(10, 0, 287, 30);

        btnLogOut.setText("Close");
        btnLogOut.setName("btnLogOut"); // NOI18N
        btnLogOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLogOutActionPerformed(evt);
            }
        });
        jInternalFrame1.getContentPane().add(btnLogOut);
        btnLogOut.setBounds(620, 0, 102, 31);

        btnSend.setText("Send");
        btnSend.setName("btnSend"); // NOI18N
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });
        jInternalFrame1.getContentPane().add(btnSend);
        btnSend.setBounds(440, 0, 102, 31);

        txtContent.setColumns(20);
        txtContent.setRows(5);
        txtContent.setName("txtContent"); // NOI18N
        jScrollPane1.setViewportView(txtContent);

        jInternalFrame1.getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(10, 239, 1046, 280);

        progressBarStatusSendEmail.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
        jInternalFrame1.getContentPane().add(progressBarStatusSendEmail);
        progressBarStatusSendEmail.setBounds(10, 520, 174, 14);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Email Info"));
        jPanel1.setToolTipText("");

        jLabel2.setText("To: ");

        jLabel3.setText("CC:");

        lblBCC.setText("BCC:");

        jLabel4.setText("Subject: ");

        jLabel1.setText("Attach File: ");

        txtTo.setName("txtTo"); // NOI18N

        txtCC.setName("txtCC"); // NOI18N

        txtBCC.setName("txtCC"); // NOI18N

        txtSubject.setName("txtSubject"); // NOI18N

        btnFileChooser.setText("Browser");
        btnFileChooser.setName("btnLogOut"); // NOI18N
        btnFileChooser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFileChooserActionPerformed(evt);
            }
        });

        btnAddBCC.setText("Add BCC");
        btnAddBCC.setName("btnLogOut"); // NOI18N
        btnAddBCC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddBCCActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30)
                .addComponent(txtTo, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30)
                .addComponent(txtCC, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(btnAddBCC, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addComponent(lblBCC, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(20, 20, 20)
                .addComponent(txtBCC, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addComponent(txtSubject, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(60, 60, 60)
                        .addComponent(txtAttachFileName, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addComponent(btnFileChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtTo, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(4, 4, 4)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtCC, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAddBCC, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(4, 4, 4)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblBCC, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtBCC, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(5, 5, 5)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtSubject, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(5, 5, 5)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtAttachFileName, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnFileChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        jInternalFrame1.getContentPane().add(jPanel1);
        jPanel1.setBounds(10, 30, 560, 200);
        jPanel1.getAccessibleContext().setAccessibleDescription("Email Info");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Enscryp Info"));
        jPanel2.setLayout(null);

        lblUserName1.setText("Select Key File For Signature:");
        lblUserName1.setToolTipText("");
        lblUserName1.setName("lblUserName"); // NOI18N
        jPanel2.add(lblUserName1);
        lblUserName1.setBounds(10, 140, 290, 14);

        txtSelectFilekey.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtSelectFilekeyActionPerformed(evt);
            }
        });
        jPanel2.add(txtSelectFilekey);
        txtSelectFilekey.setBounds(10, 110, 350, 25);

        btnSelectFileKeyAsym.setText("Browser");
        btnSelectFileKeyAsym.setName("btnLogOut"); // NOI18N
        btnSelectFileKeyAsym.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelectFileKeyAsymActionPerformed(evt);
            }
        });
        jPanel2.add(btnSelectFileKeyAsym);
        btnSelectFileKeyAsym.setBounds(370, 110, 90, 23);

        lblSelectKeyAsym.setText("Select Key File For Asymmetric Key:");
        lblSelectKeyAsym.setToolTipText("");
        lblSelectKeyAsym.setName("lblUserName"); // NOI18N
        jPanel2.add(lblSelectKeyAsym);
        lblSelectKeyAsym.setBounds(10, 90, 280, 20);
        jPanel2.add(txtSelectFileKeySignature);
        txtSelectFileKeySignature.setBounds(10, 160, 350, 25);

        btnSelectFileKeySignature.setText("Browser");
        btnSelectFileKeySignature.setName("btnLogOut"); // NOI18N
        btnSelectFileKeySignature.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelectFileKeySignatureActionPerformed(evt);
            }
        });
        jPanel2.add(btnSelectFileKeySignature);
        btnSelectFileKeySignature.setBounds(370, 160, 90, 23);

        lblSelectKeySym.setText("Select Key File For Symmetric Key:");
        lblSelectKeySym.setToolTipText("");
        lblSelectKeySym.setName("lblUserName"); // NOI18N
        jPanel2.add(lblSelectKeySym);
        lblSelectKeySym.setBounds(10, 40, 280, 20);

        txtSelectFilekeyForSymmetric.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtSelectFilekeyForSymmetricActionPerformed(evt);
            }
        });
        jPanel2.add(txtSelectFilekeyForSymmetric);
        txtSelectFilekeyForSymmetric.setBounds(10, 60, 350, 25);
        txtSelectFilekeyForSymmetric.getAccessibleContext().setAccessibleName("");

        btnSelectFileKeySym.setText("Browser");
        btnSelectFileKeySym.setName("btnLogOut"); // NOI18N
        btnSelectFileKeySym.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelectFileKeySymActionPerformed(evt);
            }
        });
        jPanel2.add(btnSelectFileKeySym);
        btnSelectFileKeySym.setBounds(370, 60, 90, 23);

        rdoEnscryNormal.setText("Enscrytion Normal");
        rdoEnscryNormal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdoEnscryNormalActionPerformed(evt);
            }
        });
        jPanel2.add(rdoEnscryNormal);
        rdoEnscryNormal.setBounds(150, 20, 150, 23);
        rdoEnscryNormal.getAccessibleContext().setAccessibleName("EnscrypType");

        rdoEnscryAdvanced.setText("Enscryption Advanced");
        rdoEnscryAdvanced.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdoEnscryAdvancedActionPerformed(evt);
            }
        });
        jPanel2.add(rdoEnscryAdvanced);
        rdoEnscryAdvanced.setBounds(320, 20, 160, 23);
        rdoEnscryAdvanced.getAccessibleContext().setAccessibleName("EnscrypType");

        rdoNotEnscryption.setText("Not Enscryption");
        rdoNotEnscryption.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdoNotEnscryptionActionPerformed(evt);
            }
        });
        jPanel2.add(rdoNotEnscryption);
        rdoNotEnscryption.setBounds(10, 20, 140, 23);

        jInternalFrame1.getContentPane().add(jPanel2);
        jPanel2.setBounds(570, 30, 490, 200);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jInternalFrame1, javax.swing.GroupLayout.PREFERRED_SIZE, 1084, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jInternalFrame1, javax.swing.GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnFileChooserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFileChooserActionPerformed
        final JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(SendMail.this);
        File fileSelected = fc.getSelectedFile();
        if(fileSelected != null) {
            txtAttachFileName.setText(fileSelected.getPath());
        }
}//GEN-LAST:event_btnFileChooserActionPerformed

    private void btnSelectFileKeyAsymActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectFileKeyAsymActionPerformed
        final JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(SendMail.this);
        File fileSelected = fc.getSelectedFile();
        if(fileSelected != null) {
            txtSelectFilekey.setText(fileSelected.getPath());
        }
}//GEN-LAST:event_btnSelectFileKeyAsymActionPerformed

    private void btnAddBCCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddBCCActionPerformed
        if(! isBCC) {
            lblBCC.setVisible(true);
            txtBCC.setVisible(true);
            btnAddBCC.setText("Remove BCC");
            isBCC = true;
        } else {
            lblBCC.setVisible(false);
            txtBCC.setVisible(false);
            btnAddBCC.setText("Add BCC");
            txtBCC.setText("");
            isBCC = false;
        }
}//GEN-LAST:event_btnAddBCCActionPerformed

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
        btnSend.setEnabled(false);
        this. setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        
        progressBarStatusSendEmail.setVisible(true);
        progressBarStatusSendEmail.setIndeterminate(true);
        
        
        try {
            SendEmail();
            
            setCursor(null);
            JOptionPane.showMessageDialog(null, "Gui mail thanh cong");
        } catch (Exception ex) {
            
            setCursor(null);
            JOptionPane.showMessageDialog(null,"Khong the thuc hien");
        }
        btnSend.setEnabled(true);
        progressBarStatusSendEmail.setIndeterminate(false);
}//GEN-LAST:event_btnSendActionPerformed

    private void btnSelectFileKeySignatureActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectFileKeySignatureActionPerformed
        final JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(SendMail.this);
        File fileSelected = fc.getSelectedFile();
        if(fileSelected != null) {
            txtSelectFileKeySignature.setText(fileSelected.getPath());
        }
    }//GEN-LAST:event_btnSelectFileKeySignatureActionPerformed

    private void txtSelectFilekeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSelectFilekeyActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtSelectFilekeyActionPerformed

    private void txtSelectFilekeyForSymmetricActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSelectFilekeyForSymmetricActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtSelectFilekeyForSymmetricActionPerformed

    private void btnSelectFileKeySymActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectFileKeySymActionPerformed
        final JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(SendMail.this);
        File fileSelected = fc.getSelectedFile();
        if(fileSelected != null) {
            txtSelectFilekeyForSymmetric.setText(fileSelected.getPath());
        }
    }//GEN-LAST:event_btnSelectFileKeySymActionPerformed

    private void rdoEnscryNormalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdoEnscryNormalActionPerformed
        type= "1";
        
        lblSelectKeySym.setVisible(true);
        txtSelectFilekeyForSymmetric.setVisible(true);
        btnSelectFileKeySym.setVisible(true);
        
        lblSelectKeyAsym.setVisible(false);
        txtSelectFilekey .setVisible(false);
        btnSelectFileKeyAsym.setVisible(false);
    }//GEN-LAST:event_rdoEnscryNormalActionPerformed

    private void rdoEnscryAdvancedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdoEnscryAdvancedActionPerformed
        type= "2";
        
        lblSelectKeySym.setVisible(true);
        txtSelectFilekeyForSymmetric.setVisible(true);
        btnSelectFileKeySym.setVisible(true);
        
        lblSelectKeyAsym.setVisible(true);
        txtSelectFilekey .setVisible(true);
        btnSelectFileKeyAsym.setVisible(true);
        
    }//GEN-LAST:event_rdoEnscryAdvancedActionPerformed

    private void rdoNotEnscryptionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdoNotEnscryptionActionPerformed
        type ="0";
        
        lblSelectKeySym.setVisible(false);
        txtSelectFilekeyForSymmetric.setVisible(false);
        btnSelectFileKeySym.setVisible(false);
        
        lblSelectKeyAsym.setVisible(false);
        txtSelectFilekey .setVisible(false);
        btnSelectFileKeyAsym.setVisible(false);
    }//GEN-LAST:event_rdoNotEnscryptionActionPerformed

    private void btnLogOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLogOutActionPerformed
        // TODO add your handling code here:
        
       this.setVisible(false);
    }//GEN-LAST:event_btnLogOutActionPerformed

    /**
     * private Mehtod ------------------------------------------------------ 
     */
    private void SendEmail() throws  Exception{

// java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        Properties props = System.getProperties();
        ThongTinTaiKhoanMailDAO mailInfo_DAO = new ThongTinTaiKhoanMailDAO();
        ThongTinTaiKhoanMail mailInfo = mailInfo_DAO.layThongTinTaiKhoanMail();
        if(mailInfo != null)
        {
            String strEmailType = "1";
            
            props.put("mail.smtp.host", mailInfo.getSmtp()); //"smtp.gmail.com"
            props.put("mail.smtp.port", mailInfo.getSmtpport()); // "587"
            props.put("mail.smtp.starttls.enable","true");
            final String login =mailInfo.getEmail(); //txtusernam.getText();
            final String pwd = mailInfo.getPassword();//txtpass.getText();
            Authenticator pa = null; 
            if (login != null && pwd != null) { 
            props.put("mail.smtp.auth", "true");
            pa = new Authenticator (){
                            @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(login, pwd);
                    }
                };

            }//else: no authentication

            Session session = Session.getInstance(props, pa);

            Message msg = new MimeMessage(session);

            msg.setFrom(new InternetAddress(mailInfo.getEmail()));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(txtTo.getText(), false));
            if( !txtCC.getText().trim().equals(""))
            {
                msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(txtCC.getText(), false));
            }
            if( !txtBCC.getText().trim().equals("") && isBCC)
            {
                msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(txtBCC.getText(), false));
            }
            Multipart mp = new MimeMultipart();
            
            // create and fill the first message part
            MimeBodyPart mbpContent = new MimeBodyPart();
            
            String strContent = txtContent.getText();
            if(type !="0")
            {
                String temp="";
                //Doi Xung
                if( ! txtSelectFilekeyForSymmetric.getText().trim().equals(""))
                {
                   byte[] ensPreShared = EmailTools.EncryptByPreSharedKey(strContent.getBytes(), txtSelectFilekeyForSymmetric.getText());
                   
                   //strContent =  new sun.misc.BASE64Encoder().encode(ensPreShared);
                   strContent = new BASE64Encoder().encode(ensPreShared);
                   //test
                   //byte[] test = new BASE64Decoder().decodeBuffer(strContent);
                   //temp = EmailTools.DecryptByPreSharedKey(test, txtSelectFilekeyForSymmetric.getText());
                }
                //Bat Doi Xung, Su Dung Cho Ma Hoa Dong Thoi
                if(type == "2" && ! txtSelectFilekey.getText().trim().equals(""))
                {
                    String strEnscryp = EmailTools.EncrypByKey(txtSelectFilekey.getText(),strContent,0 );
                    strContent = strEnscryp;
                     
                    //Test 
                   //temp = EmailTools.DecrypByKey(txtSelectFileKeySignature.getText(), strEnscryp, 1);
                   //byte[] test = new sun.misc.BASE64Decoder().decodeBuffer(temp);
                   //String demoDes = EmailTools.DecryptByPreSharedKey(test, txtSelectFilekeyForSymmetric.getText());
                  
                }
            }
            mbpContent.setText(strContent);
            
            mp.addBodyPart(mbpContent);
            File fileAttach = new File(txtAttachFileName.getText());
            if(fileAttach.exists())
            {
                strEmailType = "2";
                FileDataSource fds;
                String strFileNameEnscryp = txtAttachFileName.getText();
                if(type != "0")
                {
                    //Doi Xung
                    if( ! txtSelectFilekeyForSymmetric.getText().trim().equals(""))
                    {
                        FileInputStream fis = new FileInputStream(strFileNameEnscryp);
                        byte[] arrData = new byte[(int) fileAttach.length()];
                        fis.read(arrData);
                        fis.close();
                        
                        byte[] ensData = EmailTools.EncryptByPreSharedKey(arrData, txtSelectFilekeyForSymmetric.getText());
                        OutputStream outputWriter = new FileOutputStream(txtAttachFileName.getText()+"_EnsPre");
                        outputWriter.write(ensData);
                        strFileNameEnscryp = txtAttachFileName.getText()+"_EnsPre";
                    }
                    //Bat Doi Xung, Su Dung Cho Ma Hoa Dong Thoi
                    if(type == "2" && ! txtSelectFilekey.getText().trim().equals(""))
                    {
                        String enScrypt = fileAttach.getPath() + "_Enscrypt";
                        Cipher cipher = Cipher.getInstance("RSA");
                        EmailTools.EncryptOrDecryptFile(strFileNameEnscryp,enScrypt,txtSelectFilekey.getText(),cipher.ENCRYPT_MODE); 
                        
                        strFileNameEnscryp = enScrypt;
                    }
                }
                fds = new FileDataSource(strFileNameEnscryp);
                
                MimeBodyPart mbpAttachFile = new MimeBodyPart();
                // attach the file to the message                
                mbpAttachFile.setDataHandler(new DataHandler(fds));
                mbpAttachFile.setFileName(fds.getName());
                mp.addBodyPart(mbpAttachFile);
            }
            
            //Signature
            if(! txtSelectFileKeySignature.getText().trim().equals(""))
            {
                if(strEmailType =="1")
                {
                    //Content and Sign
                    strEmailType = "4";
                }
                else
                {
                    //Content, File Attach and Sign
                    strEmailType = "3";
                }
                
                byte[] byteSignedData = EmailTools.CreateSignature(txtSelectFileKeySignature.getText(), strContent);
                
                String temp = new sun.misc.BASE64Encoder().encode(byteSignedData);
                //byte[] test = new sun.misc.BASE64Decoder().decodeBuffer(temp);
                
                //boolean isverify = EmailTools.VerifySignature(txtSelectFilekey.getText(), test, txtContent.getText());
                //JOptionPane.showMessageDialog(null, isverify);
                
                MimeBodyPart mbpSigned = new MimeBodyPart();
                mbpSigned.setText( temp );
                mp.addBodyPart(mbpSigned);
                
            }
            
            //Enscrypt Type
            // type = 0: Not Scryption
            // type = 1: Symmetric Encryption
            // type = 2: Asymmetric Encryption
            //Email Type
            // strEmailType=1: Content
            // strEmailType=2: Content, Attach File
            // strEmailType=3: Content, Attach File, Signature
            // strEmailType=4: Content, Signature
            String temp = type + strEmailType;
            MimeBodyPart mbpEnscrypType = new MimeBodyPart();
            mbpEnscrypType.setText(temp);
            mp.addBodyPart(mbpEnscrypType);
            
            
            msg.setContent(mp);
            msg.setSubject(txtSubject.getText());
            //msg.setText(txtContent.getText());
            
            // — Set some other header information –
            msg.setHeader("X-Mailer", "LOTONtechEmail");
            msg.setSentDate(new Date());
            msg.saveChanges();
            // — Send the message –
            Transport.send(msg);
        }

    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SendMail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SendMail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SendMail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SendMail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new SendMail().setVisible(true);
                
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddBCC;
    private javax.swing.JButton btnFileChooser;
    private javax.swing.JButton btnLogOut;
    private javax.swing.JButton btnSelectFileKeyAsym;
    private javax.swing.JButton btnSelectFileKeySignature;
    private javax.swing.JButton btnSelectFileKeySym;
    private javax.swing.JButton btnSend;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.ButtonGroup buttonGroup3;
    private javax.swing.ButtonGroup buttonGroup4;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JFrame jFrame2;
    private javax.swing.JFrame jFrame3;
    private javax.swing.JFrame jFrame4;
    private javax.swing.JInternalFrame jInternalFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblBCC;
    private javax.swing.JLabel lblSelectKeyAsym;
    private javax.swing.JLabel lblSelectKeySym;
    private javax.swing.JLabel lblUserName;
    private javax.swing.JLabel lblUserName1;
    private javax.swing.JProgressBar progressBarStatusSendEmail;
    private javax.swing.JRadioButton rdoEnscryAdvanced;
    private javax.swing.JRadioButton rdoEnscryNormal;
    private javax.swing.JRadioButton rdoNotEnscryption;
    private javax.swing.JTextField txtAttachFileName;
    private javax.swing.JTextField txtBCC;
    private javax.swing.JTextField txtCC;
    private javax.swing.JTextArea txtContent;
    private javax.swing.JTextField txtSelectFileKeySignature;
    private javax.swing.JTextField txtSelectFilekey;
    private javax.swing.JTextField txtSelectFilekeyForSymmetric;
    private javax.swing.JTextField txtSubject;
    private javax.swing.JTextField txtTo;
    // End of variables declaration//GEN-END:variables
}
